package com.sc.common.lock;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class RedisDistributeLock extends AbstractDistributedLock{

    static Logger logger = LogManager.getLogger(RedisDistributeLock.class);


    private final static String LOCK_PREFIX = "redis_lock";


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean tryLock(String key) {
        return false;
    }

    @Override
    public boolean lock(String key) {
        String lock = LOCK_PREFIX + key;
        boolean flag = (Boolean) redisTemplate.execute((RedisCallback) connection -> {

            long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());

            if (acquire) {
                return true;
            } else {

                byte[] value = connection.get(lock.getBytes());

                if (Objects.nonNull(value) && value.length > 0) {

                    long expireTime = Long.parseLong(new String(value));
                    // 如果锁已经过期
                    if (expireTime < System.currentTimeMillis()) {
                        // 重新加锁，防止死锁
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
        return flag;
    }

    @Override
    public boolean lock(String key,long time, TimeUnit unit) {
        return false;
    }

    @Override
    public boolean unLock(String key) {
        logger.info("解锁分布式锁");
        return redisTemplate.delete(key);
    }
}
